package net.luoran.dvm.core;

import cn.hutool.json.JSONUtil;
import net.luoran.dvm.common.base.Result;
import net.luoran.dvm.common.base.ResultEnum;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResultHandler implements ResponseBodyAdvice<Object> {

    //判断支持的类型
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 判断为null构建Result对象进行返回
        if (o == null) {
            return Result.success(null);
        }
        // 判断是Result子类或其本身就返回Object o本身，因为有可能是接口返回时创建了Result,这里避免再次封装
        if (o instanceof Result) {
            return (Result<Object>) o;
        }
        // String特殊处理，否则会抛异常
        if (o instanceof String) {
            return JSONUtil.formatJsonStr(Result.success(o).toString());
        }
        return Result.success(o);
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        e.printStackTrace();
        String message = e.getMessage();
        String substr = message.substring(message.length() - 5);
        if (substr.equals("[401]")) {
            return Result.build(ResultEnum.NO_LOGIN);
        } else if (substr.equals("[403]")) {
            return Result.build(ResultEnum.NO_AUTH);
        }
        return Result.error(e.getMessage() == null ? e.toString() : e.getMessage());
    }

}
